'use strict';
const dynamodb = require('../database/dynamodb');
const config = require('../config');
const security = require('../utils/security');

const typePhoneLogin = 1;
const typeFindPw = 2;

function getCode(phone, type, callback) {
    const params = {
        TableName: config.database.VerifyCode,
        Key: {
            'phone': phone,
            'type': type,
        },
    };
    dynamodb.get(params, callback);
}

function saveCode(phone, code, type, callback) {
    const params = {
        TableName: config.database.VerifyCode,
        Item: {
            'phone': phone,
            'code': code,
            'type': type,
            'date': Date.now(),
        },
    };
    dynamodb.put(params, callback);
}

function saveLoginCode(phone, code, callback) {
    saveCode(phone, security.md5(code, '#ssyer.com#login#'), typePhoneLogin, callback);
}

function saveFindPwCode(phone, code, callback) {
    saveCode(phone, security.md5(code, '#ssyer.com#getUpdateCode#'), typeFindPw, callback);
}

function getLoginCode(phone, callback) {
    getCode(phone, typePhoneLogin, callback);
}

function getFindPwCode(phone, callback) {
    getCode(phone, typeFindPw, callback);
}

module.exports = {
    getLoginCode: getLoginCode,
    getFindPwCode: getFindPwCode,
    saveLoginCode: saveLoginCode,
    saveFindPwCode: saveFindPwCode,
};